<?php
//微信消费券相关服务

namespace App\Services\Wx;

//use EasyWeChat\Factory;
use App\Models\MonitorModel;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Pay\Application;
use mysql_xdevapi\Exception;


class WxCoupon
{

    public $app;

    private $mainUrl = 'https://api.mch.weixin.qq.com';

    public function __construct()
    {
        //        $config = [
        //            'app_id' => WxConfig::$appId,
        //            'secret' => WxConfig::$secret,
        //
        //            // 下面为可选项
        //            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        //            'response_type' => 'array',
        //        ];
        //
        ////        $this->app = Factory::officialAccount($config);
        //        $this->app = Factory::payment($config);

        $certBasePath = base_path().'/storage/cert/';
        $config = [
            'mch_id'         => env('MCHID'),

            // 商户证书
            'private_key'    => $certBasePath.'apiclient_key.pem',
            'certificate'    => $certBasePath.'apiclient_cert.pem',

            // v3 API 秘钥
            'secret_key'     => env('V3_SECRET_KEY'),

            // v2 API 秘钥
            'v2_secret_key'  => '',

            // 平台证书：微信支付 APIv3 平台证书，需要使用工具下载
            // 下载工具：https://github.com/wechatpay-apiv3/CertificateDownloader
            'platform_certs' => [
                // 请使用绝对路径
                // '/path/to/wechatpay/cert.pem',
            ],

            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http'           => [
                'throw'   => false, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.mch.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
            ],
        ];
        $this->app = new Application($config);
    }

    public function getApp()
    {
        return $this->app;
    }

    /**
     * 创建领券人政务凭证
     * @param $openid
     * @return array
     */
    public function createUserCert($openid, $activityId = 0)
    {
        $url = "/v3/gov/special-population/credentials";
        try {

            $specialPopulationType = MonitorModel::where('id', $activityId)
                ->value('wx_cert_special_people_code');
            $api = $this->app->getClient();
            $res = $api->postJson($url, [
                'institution_id'          => WxConfig::$userCertInstitutionId,
                'special_population_type' => $specialPopulationType,
                'appid'                   => env('APPID'),
                'openid'                  => $openid,
            ])->toArray();
        } catch (\Exception $e) {
            return [];
        }

        return $res;
    }

    /**
     * 协助认证政务凭证
     * @param $openid
     * @return array
     */
    public function createUserCertAssist ($openid, $activityId = 0)
    {
        /*$wxTransfer = new WxTransfer();
        dd($wxTransfer->getPlatFormCertList());*/
        $url = "/v3/gov/special-population/credentials/related";    // 协助认证
        try {
            $userName = '梁子标';
            $idNumber = '440402198310049030';
            //用户名敏感信息加密，rsa标准算法
            $userNameEnStr = self::getRiskStrEncrypt($userName);
            $idNumberNameEnStr = self::getRiskStrEncrypt($idNumber);

            $activity = MonitorModel::where('id', $activityId)
                ->select('assist_wx_cert_special_people_code', 'assist_institution_id')
                ->first();
            $specialPopulationType = $activity['assist_wx_cert_special_people_code'];
            $institutionId = $activity['assist_institution_id'];
            $api = $this->app->getClient();
            $res = $api->postJson($url, [
                'institution_id'          => $institutionId,
                'special_population_type' => $specialPopulationType,
                'appid'                   => env('APPID'),
                'openid'                  => 'oBCaZ6xgdZtSkp6CJTdiwyreAT1c',
                'principal'               => [
                    'real_name' => $userNameEnStr,
                    'id_card_number' => $idNumberNameEnStr
                ]
            ],[
                'headers' => [
                    'Wechatpay-Serial' => '1F2337C2220479E1114C040041B71600D0DB7A46',
                ],
            ])->toArray();
        } catch (\Exception $e) {
            return [];
        }
        return $res;
    }

    /**
     * 敏感词加密，rsa标准算法
     * @param $str
     * @return string
     */
    private static function getRiskStrEncrypt($str)
    {
        //$str是待加密字符串
        $public_key_path = base_path().'/storage/cert/platform_cert.pem';;
        $public_key = file_get_contents($public_key_path);
        $encrypted = '';
        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码
            $sign = base64_encode($encrypted);
        } else {
            return '';
        }
        return $sign;
    }

    /**
     * 查询券批次详情
     * @param $stockId
     * @return array
     */
    public function getCouponStockDetail($stockId)
    {
        $url = 'v3/marketing/favor/stocks/'.$stockId;

        try {
            $api = $this->app->getClient();
            $res = $api->get($url, [
                'stock_creator_mchid' => env('MCHID'),
            ])->toArray();
        } catch (\Exception $e) {
            return [];
        }

        return $res;
    }

    /**
     * 查询用户领取的代金券详情
     * @param $stockId
     * @return array
     */
    public function getCouponDetail($openid, $couponId)
    {
        $appid = env('APPID');
        $url = "v3/marketing/favor/users/$openid/coupons/$couponId?appid=$appid";
        try {
            $api = $this->app->getClient();
            $res = $api->get($url)->toArray();
        } catch (\Exception $e) {
            return [];
        }

        return $res;
    }



    /**
     * 领取消费券
     * @param $openid
     * @param $stockId
     * @param $outRequestNo
     * @return array
     * 文档：https://pay.weixin.qq.com/docs/merchant/apis/cash-coupons/coupon/send-coupon.html
     */
    public function receiveCoupon($openid, $stockId, $outRequestNo)
    {
        $url = "/v3/marketing/favor/users/{$openid}/coupons";
        try {
            $api = $this->app->getClient();
            $body = [
                'stock_id'            => (string)$stockId,
                'out_request_no'      => $outRequestNo,
                'appid'               => env('APPID'),
                'stock_creator_mchid' => (string) env('MCHID'),
            ];
            $res = $api->postJson($url, $body)->toArray();
        } catch (\Exception $e) {
            return [];
        }

        return $res;
    }

}
